<template>
  <div class="gap-col-16 mt-4">
    <DateRangeInput v-model="dateRange"></DateRangeInput>
    <FilterTabs v-model="selectedFilter" :items="filters"></FilterTabs>
    <div class="text-end text-input font-size-14 font-style-normal font-weight-500 line-height-140" @click="open()">
      {{ $t('info.watchAllData') }}
    </div>
    <div class="gap-col-16">
      <div v-for="(media, index) in medias" :key="`earn-media-info-${index}`">
        <EarnMediaInfo :media="media"></EarnMediaInfo>
      </div>
      <div v-if="isBottom" class="d-flex justify-center align-center">
        <div class="text-input font-size-14 font-style-normal font-weight-500 line-height-140">
          {{ $t('common.noMore') }}
        </div>
      </div>
      <div v-else v-intersect="onIntersect" class="d-flex justify-center align-center">
        <div v-show="isFetching">{{ $t('common.loading') }}</div>
      </div>
    </div>
    <div class="tail-size-96"></div>
  </div>
</template>
<script setup>
import { onMounted, ref, shallowRef, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useEarnStore } from '@/store/earn.js'
import { toDateYmd } from '@/utils/string-helper'
import DateRangeInput from '@/components/form/DateRangeInput.vue'
import EarnMediaInfo from '@/components/mine/EarnMediaInfo.vue'
import FilterTabs from '@/components/mine/FilterTabs.vue'
import { EARN_MEDIA_FILTER } from '@/constant'
import API from '@/http'

const earnStore = useEarnStore()
const { open, filters } = earnStore
const { selectedFilter, startDate, endDate } = storeToRefs(earnStore)

const dateRange = shallowRef([startDate.value, endDate.value])
watch(dateRange, (newVal) => {
  startDate.value = newVal[0]
  endDate.value = newVal[1]
  reload()
})

const medias = ref([])

watch(selectedFilter, () => reload())

const isFetching = ref(false)
const isBottom = ref(false)
const page = ref(0)
const limit = ref(10)

const fetch = async () => {
  try {
    isFetching.value = true
    page.value += 1

    // 如果是 TOP 5, 只能拿一次
    if (page.value > 1 && selectedFilter.value.value === EARN_MEDIA_FILTER.TOP5_VIEW) {
      isFetching.value = false
      isBottom.value = true
      return
    }

    const data = {
      page: page.value,
      limit: limit.value,
      type: selectedFilter.value.value,
      start: toDateYmd(startDate.value),
      end: toDateYmd(endDate.value),
    }

    const response = await API.Earn.media({ data })
    console.log(`[API.Earn.media]`, response)
    isFetching.value = false
    isBottom.value = response.length <= 0
    medias.value = [...medias.value, ...response]
  } catch (e) {
    console.error(e)
  }
}

onMounted(() => fetch())

const onIntersect = (value) => {
  if (value === false || isFetching.value || isBottom.value) return
  fetch()
}

const reload = () => {
  medias.value = []
  page.value = 0
  isBottom.value = false
  isFetching.value = false
  fetch()
}
</script>
